/**
*	nodejs 开发队列服务
*	开发者：雨中磐石(rainrock)
*	网址：http://www.rockoa.com/
*	时间：2019-07-17
*/


function rockQueueServer(conf){
	var me = this;
	this.rockBase = false;
	this.starturl = '';
	this.reimserver = {};
	for(var i in conf)this[i] = conf[i];
	
	
	//需要运行的队列服务
	this.queuelist	= {};
	
	
	this.run = function(){
		this.getqueuelist();
		//this.udpserver();
		this.httpserver();
		this.lasttime = this.rockBase.getTime();
		this.lastMinutes = this.rockBase.Minutes;
		setInterval(function(){me.startrunurl();},1000);
	};
	
	//开启即时
	this.startrunurl = function(){
		var time = this.rockBase.getTime();
		this.queuerun(time);
		if(time!=this.lasttime+1)this.queuerun(this.lasttime+1); //防止跳过秒
		this.lastMinutes = this.rockBase.Minutes;
		this.lasttime 	 = time;
	};
	
	this.queuerun	= function(time){
		var key = 'a'+time+'';
		var rar = this.queuelist[key],tag,d;
		if(rar){
			for(tag in rar){
				d = rar[tag];
				if(d.qtype=='url')this.rockBase.runurl(d.url); //运行URL
				if(d.qtype=='cmd')this.rockBase.execcmd(d.url);
			}
			this.queuelist[key] = false;//注销
		}
		if(this.reimserver.timerun)this.reimserver.timerun(time);
		var sy = time % 300;
		if(sy == 0)this.starttask(time);
	};
	
	this.urlencode=function(url){
		var str = url.toString().toLowerCase();
		str = str.replace('://','[HTTP]');
		str = str.replace('?','[WEN]');
		str = str.replace(/\&/gi,'[AND]');
		str = str.replace(/\//gi,'[XIE]');
		return str;
	};
	
	//获取未执行的队列
	this.getqueuelist=function(){
		
	};
	this.getqueuelistshow=function(bstr){
		var data,rows,i,len;
		data = JSON.parse(bstr);
		
		rows = data.queue;
		len  = rows.length;
		this.rockBase.debug('queuelist:('+len+')');
		for(i=0;i<len;i++){
			me.addqueue(rows[i]);
		}
	};
	
	
	//添加到队列中
	this.addqueue	= function(d){
		var key = 'a'+d.runtime+'';
		var tags= 'tags_'+d.id+'';
		if(!this.queuelist[key])this.queuelist[key] = {};
		this.queuelist[key][tags] = d;
	};
	
	//运行结果更新
	this.runresult = function(id, msg){
		
	};
	
	
	//---udp- 服务器，用来推送---
	this.udpserver	= function(){
		var dgram 	= require("dgram");
		var server  = dgram.createSocket("udp4");
		server.on("open", function (err) {
			console.log('open');
		});
		server.on("error", function (err) {
			me.rockBase.debug("rockqueue error:" + err.stack);
			server.close();
		});

		server.on("message", function (msg, rinfo){
			var msg	= msg.toString();
			me.rockBase.debug(msg);
			try{
				var data = JSON.parse(msg);
				me.udpmessage(data);
			}catch(e){}
		});

		server.on("listening", function () {
			var address = server.address();
			me.rockBase.debug("rockqueue start success listening:" + address.address + ":" + address.port);
			setTimeout(function(){me.initstarturl()},1000);
		});
		
		server.bind(this.config.port, this.config.ip);
	}
	
	/**
	*	创建http服务器
	*/
	this.httpserver=function(){
		const http = require('http');
		const urlObj  = require("url");
		const server = http.createServer(function(req, res){
			var url = req.url.toString(),bstr='ok',method = req.method;

			var obj = urlObj.parse(req.url, true);
			var query = obj.query;
			var atype = query.atype;
			if(atype=='send' && query.data){
				var data = decodeURI(query.data);
				me.rockBase.debug(data);
				bstr = me.udpmessage(JSON.parse(data));
				if(!bstr){bstr='ok';}else{if(typeof(bstr)=='object')bstr=JSON.stringify(bstr);}
			}
			
			res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
			res.write(bstr);
			res.end();
		});
		server.listen(this.config.port, this.config.ip,function() {
			var address = server.address();
			me.rockBase.debug("rockqueue start success listening:" + address.address + ":" + address.port);
			setTimeout(function(){me.initstarturl()},1000);
		});
	}
	
	/**
	*	接收到数据处理[{type:"cmd",url:''}]
	*/
	this.udpmessage=function(ret){
		if(!ret[0])ret=[ret];
		var qtype,i,len=ret.length,d,cont;
		var ntime = this.rockBase.getTime(),barr='';
		for(i=0;i<len;i++){
			d 	 = ret[i];
			qtype = d.qtype;
			var runtime = d.runtime;
			if(!runtime || runtime<=ntime){
				if(qtype=='url'){
					this.rockBase.runurl(d.url); //运行URL
				}
				if(qtype=='cmd'){
					cont = d.url;
					if(cont.indexOf('php')>-1 || cont.indexOf('writer_pdf_Export')>-1)this.rockBase.execcmd(d.url);
				}
				if(qtype=='starturl'){
					this.setstarturl(d);
				}
				if(qtype=='reim'){
					barr = me.reimserver.wsreimpush(d);
				}
			}else{
				this.addqueue(d); //添加到队列中
			}
		}
		return barr;
	};
	this.initstarturl=function(){
		this.starturla = [];
		var path = ''+__dirname+'/starturl.json';
		if(this.rockBase.getFsobj().existsSync(path)){
			var json = this.rockBase.getFsobj().readFileSync(path);
			var msg  = json.toString();
			if(msg){
				this.starturla = JSON.parse(msg);
			}
		}
		var i,len=this.starturla.length,d1;
		for(i=0;i<len;i++){
			d1 = this.starturla[i];
			if(d1.url && !d1.type)this.rockBase.runurl(d1.url);
		}
	}
	
	//设置初始加载url
	this.setstarturl=function(d){
		var i,len=this.starturla.length,d1,arr=[],str='',bo=false;
		for(i=0;i<len;i++){
			d1 = this.starturla[i];
			if(d.recid==d1.recid){
				d1 = d;
				bo=true;
			}
			if(d1.url)arr.push({
				'recid':d1.recid,
				'url':d1.url,
				'type':(d1.type) ? d1.type : ''
			});
		}
		if(!bo && d.url)arr.push({
			'recid':d.recid,
			'url':d.url,
			'type':(d.type) ? d.type : ''
		});
		if(arr.length>0)str = JSON.stringify(arr);
		this.starturla= arr;
		this.rockBase.getFsobj().writeFile(''+__dirname+'/starturl.json', str, function(err){});
	}
	
	//运行计划任务(5分钟运行一次)
	this.starttask=function(time){
		var i,len=this.starturla.length,d,url;
		for(i=0;i<len;i++){
			d 	= this.starturla[i];
			url = d.url;
			if(url && d.type=='task'){
				if(url.indexOf('http')==0){
					this.rockBase.runurl(url);
				}else{
					this.rockBase.execcmd(url);
				}
			}
		}
	}
}

module.exports = rockQueueServer;